# algorithm/views.py
from algorithm.models import UserTagMastery, UserProblemRecommendation, UserComprehensiveLevel, TagDependency
from problems.serializers import ProblemSerializer
from rest_framework.authtoken.models import Token
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import authentication_classes, permission_classes
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.contrib.auth.models import User
import io
import sys
from django.http import HttpResponse
from django.http import JsonResponse
from rest_framework_simplejwt.authentication import JWTAuthentication
from django.db.models import Count
from recommendation.models import SolvedProblem
from tag.models import AlgorithmTag
from utils.logging_utils import log_request_response


@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def frontend_get_user_tag_mastery(request):
    user = request.user

    # 获取用户的掌握信息数据
    mastery_data = UserTagMastery.objects.filter(user=user).select_related('tag')  # 预加载 tag 数据
    mastery_info = {}

    # 序列化和构造数据
    for entry in mastery_data:
        tag_name = entry.tag.tag_name  # 直接访问 tag 的 tag_name
        mastery_info[tag_name] = {
            'mastery_score': entry.mastery_score,
            'mastery_level': entry.mastery_level,
            'recommendation_score': entry.recommendation_score
        }

    return Response({
        'tag_mastery_data': mastery_info
    })



@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])  # 仅允许已认证的用户执行操作
@log_request_response
def initialize_user_tag_mastery(request):
    user_id = request.user.id  # 假设用户已通过认证，并从请求的用户中获取用户ID

    try:
        # 调用初始化方法
        UserTagMastery.initialize_user_tag_mastery(user_id)
        return Response({"message": "User tag mastery initialization successful."}, status=status.HTTP_200_OK)
    except User.DoesNotExist:
        # 如果用户不存在，返回错误
        return Response({"error": "User not found."}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        # 捕捉其他可能的错误，并返回服务器错误状态码
        return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def get_user_tag_mastery_info(request):
    user_id = request.user.id  # 获取认证用户的ID

    # 重定向标准输出到字符串流
    old_stdout = sys.stdout
    sys.stdout = mystdout = io.StringIO()

    try:
        # 调用打印方法
        UserTagMastery.print_user_tag_mastery_info(user_id)
        # 获取输出内容
        output = mystdout.getvalue()
        sys.stdout = old_stdout  # 恢复标准输出
        return HttpResponse(output, content_type="text/plain")
    except Exception as e:
        sys.stdout = old_stdout  # 确保即使出现错误也能恢复标准输出
        return Response({'error': str(e)}, status=400)


@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def clear_user_tag_mastery(request):
    user_id = request.user.id  # 假定请求的用户就是目标用户，或者从请求中提取特定用户ID

    try:
        result = UserTagMastery.clear_user_tag_mastery(user_id)
        return Response({"message": f"Successfully cleared mastery records for user with ID {user_id}."})
    except Exception as e:
        return Response({"error": str(e)}, status=400)


@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def get_user_comprehensive_level_info(request):
    user_id = request.user.id  # 获取认证用户的ID

    # 重定向标准输出到字符串流
    old_stdout = sys.stdout
    sys.stdout = mystdout = io.StringIO()

    try:
        # 调用打印方法
        UserComprehensiveLevel.print_user_comprehensive_level_info(user_id)
        # 获取输出内容
        output = mystdout.getvalue()
        sys.stdout = old_stdout  # 恢复标准输出
        return HttpResponse(output, content_type="text/plain")
    except Exception as e:
        sys.stdout = old_stdout  # 确保即使出现错误也能恢复标准输出
        return Response({'error': str(e)}, status=400)


@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def generate_user_comprehensive_level(request):
    user_id = request.user.id
    try:
        # 调用初始化方法
        UserComprehensiveLevel.create_or_update_user_level(user_id)
        return Response({"message": "User comprehensive level generation successful."}, status=status.HTTP_200_OK)
    except User.DoesNotExist:
        # 如果用户不存在，返回错误
        return Response({"error": "User not found."}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        # 捕捉其他可能的错误，并返回服务器错误状态码
        return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def get_user_problem_recommendation_score_info(request):
    user_id = request.user.id  # 获取认证用户的ID

    # 重定向标准输出到字符串流
    old_stdout = sys.stdout
    sys.stdout = mystdout = io.StringIO()

    try:
        # 调用打印方法
        UserProblemRecommendation.print_user_problem_recommendation_score_info(user_id)
        # 获取输出内容
        output = mystdout.getvalue()
        sys.stdout = old_stdout  # 恢复标准输出
        return HttpResponse(output, content_type="text/plain")
    except Exception as e:
        sys.stdout = old_stdout  # 确保即使出现错误也能恢复标准输出
        return Response({'error': str(e)}, status=400)


@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def initialize_user_problem_recommendation_score(request):
    user_id = request.user.id
    try:
        # 调用初始化方法
        UserProblemRecommendation.initialize_user_problem_recommendation_scores(user_id)
        return Response({"message": "User problem recommendation score initialization successful."}, status=status.HTTP_200_OK)
    except User.DoesNotExist:
        # 如果用户不存在，返回错误
        return Response({"error": "User not found."}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        # 捕捉其他可能的错误，并返回服务器错误状态码
        return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


from .serializers import UserComprehensiveLevelSerializer, UserTagMasterySerializer, TagDependencySerializer, \
    FrontEndTagDependencySerializer


@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def get_user_comprehensive_level(request):
    """
    获取请求用户的综合水平信息。
    """
    try:
        user_level = UserComprehensiveLevel.objects.get(user=request.user)
        serializer = UserComprehensiveLevelSerializer(user_level)
        return Response(serializer.data, status=status.HTTP_200_OK)
    except UserComprehensiveLevel.DoesNotExist:
        return Response({"error": "User comprehensive level not found."}, status=status.HTTP_404_NOT_FOUND)


@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def get_user_tag_mastery(request):
    """
    获取请求用户的所有标签掌握记录。
    """
    tag_mastery_records = UserTagMastery.objects.filter(user=request.user)
    serializer = UserTagMasterySerializer(tag_mastery_records, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)


@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])  # 仅允许已认证的用户执行操作
def initialize_user_mastery_levels_view(request):
    user_id = request.user.id  # 从请求中获取经过认证的用户ID

    try:
        # 调用初始化用户掌握级别的方法
        UserTagMastery.initialize_user_mastery_levels(user_id)
        return Response({"message": "User mastery levels initialization successful."}, status=status.HTTP_200_OK)
    except User.DoesNotExist:
        # 如果用户不存在，返回错误信息
        return Response({"error": "User not found."}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        # 捕捉其他异常并返回服务器错误状态码
        return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def frontend_get_tag_dependencies(request):
    """
    获取所有的 TagDependency 依赖关系
    """
    dependencies = TagDependency.objects.all()
    serializer = TagDependencySerializer(dependencies, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)


@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def frontend_get_tag_dependencies_for_liu(request):
    """
    获取所有的 TagDependency 依赖关系
    """
    dependencies = TagDependency.objects.all()
    serializer = FrontEndTagDependencySerializer(dependencies, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)
